import React, { useState, useEffect, lazy } from 'react'
import { SearchBar, Swiper, Grid, Loading } from 'antd-mobile'
import './style.scss'
import { useHistory, Route } from "react-router-dom";
import { GetHomeLists } from "../../../request/api";
import BackTop from "../../../components/backTop/index";

export default function Home({ route }) {
  const [value, setValue] = useState('')
  const [iftop, setIftop] = useState(false)
  const [isLoading, setLoading] = useState(true)
  const [banner, setBanner] = useState([])//轮播图
  const [channel, setChannel] = useState([])//快捷导航
  const [brandList, setBrandList] = useState([])//品牌制造商
  const [newGoodsList, setNewGoodsList] = useState([])//新品首发

  useEffect(() => {
    //首页数据请求
    GetHomeLists().then((res) => {
      if (res.data.errno === 0) {
        let { banner, channel, brandList, newGoodsList } = res.data.data;
        setBanner(banner);
        setChannel(channel);
        setLoading(false);
        setBrandList(brandList);
        setNewGoodsList(newGoodsList);
      }
    });
  }, [])

  const swiperItems = banner.map((item, index) => (
    <Swiper.Item key={index}>
      <img
        src={item.image_url}
        width="100%"
      />
    </Swiper.Item>
  ))
  const gridItems = channel.map((item, index) => (
    <Grid.Item key={index}>
      <div className="grid">
        <img
          src={item.icon_url}
          width="100%"
        />
        <span>{item.name}</span>
      </div>
    </Grid.Item>
  ))
  const history = useHistory()

  const goBrandDetail = (value) => {
    history.push({
      pathname: `/brandDetail/${value}`,
      state: {
        showTab: 'show',
      }
    })
  }

  return (
    <div id="home-root">
      <SearchBar placeholder='请输入内容' value={value} showCancelButton />
      {isLoading && <Loading color='primary' />}
      <Swiper autoplay>{swiperItems}</Swiper>
      <Grid columns={5} gap={8}>
        {gridItems}
      </Grid>
      <div className="brand">
        <div className="home_title">品牌制造商提供</div>
        <ul>
          {brandList.map((item, index) => (
            <li key={index} onClick={() => goBrandDetail(item.id)}>
              <img src={item.pic_url} />
              <h4>{item.name}</h4>
              <p>￥{item.floor_price}元</p>
            </li>
          ))}

        </ul>
      </div>
      <div className="new">
        <div className="home_title">周一周四·新品首发</div>
        <ul>
          {newGoodsList.map((item, index) => (
            <li key={index}>
              <img src={item.list_pic_url} />
              <div>{item.name}</div>
              <p>￥{item.retail_price}元</p>
            </li>
          ))}
        </ul>
      </div>
      <BackTop iftop={iftop} setIftop={(e) => setIftop(e)} />
    </div >
  )
}